package com.gxa.community.admin.controller.system;

import com.gxa.community.admin.realm.Auth2Token.Auth2Token;
import com.gxa.community.admin.service.system.LoginService;
import com.gxa.community.admin.util.JwtUtil;
import com.gxa.community.admin.util.RedisUtils;
import com.gxa.community.core.common.ResultMsg;
import com.gxa.community.core.pojo.domain.Admin;
import com.gxa.community.core.utils.R;
import com.wf.captcha.SpecCaptcha;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Slf4j
@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;
    RedisUtils redisUtils = new RedisUtils();

    @ApiOperation("退出登录")
    @ResponseBody
    @PostMapping("/loginOut")
    public R loginOut(HttpServletRequest request) {
        //获取当前申请用户的id
        String token = (String) request.getAttribute("token");
        boolean result = loginService.loginOut(JwtUtil.getClaim(token, "loginAct").asString(),
                JwtUtil.getClaim(token, "userId").asInt());
        return result ? R.ok(ResultMsg.LOGINOUT_SUCCESS.getMsg()) : R.error(ResultMsg.LOGINOUT_FAILURE.getMsg());
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/queryUserInfoByUserId")
    public R queryUserInfoByUserId(HttpServletRequest request) {
        String token = request.getHeader("token");

        if (ObjectUtils.isEmpty(token))
            return R.error(ResultMsg.LOGIN_ACCOUNT_GETUSERINFO_FAILURE.getMsg());

        return loginService.queryUserInfoByUserId(token);
    }


    @ApiOperation("登录")
    @ResponseBody
    @PostMapping("/login")
    public R login(String username, String password, String verCode, String verKey) {
        // 获取redis中的验证码
        String redisCode = (String) redisUtils.get(verKey);
        // 判断验证码
        if (verCode == null || !redisCode.equals(verCode.trim().toLowerCase())) {
            return R.error(ResultMsg.SMS_PHONE_CODE_ERROR.getMsg());
        }
        Admin admin = null;
        try {
            admin = loginService.queryAdminByName(username);
        } catch (Exception e) {
            return R.error("账户异常");
        }
        String sign = JwtUtil.sign(username, JwtUtil.encodePsw(password, admin.getSalt()), admin.getId(), admin.getLoginAct());
        //进行登录
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new Auth2Token(sign));
        } catch (Exception e) {
            return R.error(ResultMsg.LOGIN_FAILURE.getMsg());
        }
        //登录成功设置用户状态
        loginService.updateAdminLoginStatus(username,admin.getId());
        return R.ok(ResultMsg.LOGIN_SUCCESS.getMsg()).put("token",sign);
    }

    @ApiOperation("生成验证码")
    @GetMapping("/captcha")
    public R login(HttpServletRequest request, HttpServletResponse response) {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key = UUID.randomUUID().toString();
        // 存入redis并设置过期时间为1分钟
        redisUtils.setCode(key, verCode, 1);
        // 将key和base64返回给前端
        return R.ok().put("key", key).put("image", specCaptcha.toBase64());
    }
}
